package com.pw.demo3.controller;

import com.pw.demo3.bean.Employee;
import com.pw.demo3.service.impl.EmployeeServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@Controller
public class indexController {

    @Autowired
    EmployeeServiceImpl employeeService;

    @RequestMapping(value = "/")
    public String homePage() {
        return "login";
    }


    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(Model model,@RequestParam String username,
                                     @RequestParam String password) {
        Map<String, Object> map = new HashMap<>();
        //获取当前用户
        Subject subject=SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            map.put("success", false);
            map.put("msg","用户名不存在");
            return map;
        }catch (IncorrectCredentialsException e){
            map.put("success", false);
            map.put("msg","密码错误");
            return map;
        }catch (Exception e){
            map.put("success", false);
            map.put("msg", "登陆失败");
            return map;
        }
        map.put("success", true);
        return map;
    }

    //退出登录
    @RequestMapping("/logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            subject.logout();
        }
        return "login";
    }

    //无权限
    @RequestMapping("/noPermission")
    public String nopermission(){
        return "views/common/nopermission";
    }
    //错误
    @RequestMapping("/toError")
    public String toerror(){
        return "views/common/error";
    }
}
